import pinia from "../stores/defaultPinia";
import router, { routers } from "./index";
import { AxiosCanceler } from "@/api/helper/axiosCancel";
import { usePermissionStore } from "@/stores/permissionStore";
import { useAppStore } from "@/stores/appStore";
import { searchRoute, handleRouter } from "@/utils/util";
import { filterRoutes } from "@/utils/system/system";
import { usePageLoading } from "@/hooks/usePageLoading";
const permissionStore = usePermissionStore(pinia);
const appStore = useAppStore(pinia);

const axiosCanceler = new AxiosCanceler();

const { loadStart, loadDone } = usePageLoading();
/**
 * 路由导航守卫
 */
router.beforeEach(async (to, from, next) => {
  loadStart();
  const path = to.path;
  const route = searchRoute(path, routers);
  // * 在跳转路由之前，清除所有的请求
  axiosCanceler.removeAllPending();
  // * 跳转之前先设置当前页面路劲
  if (!route.meta?.requireAuth ?? true) {
    next();
    return;
  }
  // * 判断是否有Token
  const token = window.localStorage.getItem("accessToken");
  if (!token) {
    next("/loginPage");
    return;
  }
  await permissionStore.setMenuListAction();
  let dynamicRouter = permissionStore.getMenuList(); // 权限判断
  dynamicRouter = handleRouter(dynamicRouter, filterRoutes.slice(0)); // filterRoutes 是需要过滤掉的路由，例如404，以便后期做一些特殊的路由判断
  if (dynamicRouter.indexOf(path) === -1) {
    next("/404");
    return;
  }
  next();
});

router.afterEach((to) => {
  if (filterRoutes.indexOf(to.path) < 0) {
    // 如果访问的页面路由不在404路由表里，则保存
    window.localStorage.setItem("lastRoute", to.path);
  }
  appStore.addOpenRouters(to);
  appStore.saveCurrentRouter(to);
  loadDone();
});
